const csv = require("csv");
const fs = require("fs");
const path = require("path");


/*
fs.readFile(path.join(__dirname,"./normalized_result.csv"),async (err,data)=>{
  if(err){
    debugger
    return;
  }
  let d_results = data.toString();
  let d_location = await readLocation();
  csv.parse(d_results,{},(err,result_records,results_info)=>{
    // debugger
    csv.parse(d_location,{},(err,location_records,location_info)=>{
      // debugger
      result_records
      location_records
      let my_want = [];
      for(let i = 0;i<result_records.length;i++){
        let xy_string = result_records[i][0];
        let xy = xy_string.split(" ").map(e=>JSON.parse(e));
        // debugger
        let loc = JSON.parse(location_records[i][0]);
        my_want.push({
          x:xy[0],
          y:xy[1],
          location:loc
        })
      }
      fs.writeFile(path.join(__dirname,"./t-sne.json"),JSON.stringify(my_want),{},(err)=>{
        if(err){
          debugger
        }
        process.exit();
      })
    })
  });
  // debugger
});
*/

/**
 * 
 * @param {Number} index 
 */
function readLocation(index) {
  return new Promise(resolve => {
    fs.readFile(path.join(__dirname, `./projected_location_${index}.csv`), (err, data) => {
      if (err) {
        debugger
      }
      resolve(
        data.toString()
      )
    })
  })
}

/**
 * @returns {Promise<{records:Any}>}
 * @param {String} data 
 */
function csv_parse(data) {
  return new Promise(resolve => {
    csv.parse(data, {}, (err, records) => {
      if (err) {
        debugger
        return;
      }
      resolve({
        records: records
      })
    })
  })
}



(async () => {
  /**@type {Array<{index:Number,d:String}>} */
  let csv_raws = [];
  for (let i = 1; i <= 19; i++) {
    if (i == 7) continue;
    let O_READ = await readLocation(i);
    csv_raws.push({ index: i, d: O_READ });
  }

 
  let projected_data = {}
  for (let cr of csv_raws) {
    let location = cr.index;
    let parsed = await csv_parse(cr.d);
    projected_data[location] = [];
    /**@type {Array<Array<String>>} */
    let records = parsed.records;
    for (let o of records) {
      let x = JSON.parse(o[0]);
      let y = JSON.parse(o[1]);
      
      projected_data[location].push({
        x: x, y: y, location: location
      })
    }
    // debugger
  }

  let json_str = JSON.stringify(projected_data);
  fs.writeFile(path.join(__dirname,"./tsnev2.json"),json_str,(err)=>{
    debugger
  })

  // debugger
})();